﻿using MediatR;
using Swork03_28.Api.Application.Commands.TraceableCommand;
using Swork03_28.Domain;
using Swork03_28.Domain.Dto;
using Swork03_28.Services.Interface;

namespace Swork03_28.Api.Application.CommandHandlers.TraceableHandler
{
    public class TraceableSelectCommandHandler : IRequestHandler<TraceableSelectCommand, PageInfo>
    {

        private readonly ITraceableService traceableService;
        private readonly IGoodsService goodsService;

        public TraceableSelectCommandHandler(ITraceableService traceableService, IGoodsService goodsService)
        {
            this.traceableService = traceableService;
            this.goodsService = goodsService;
        }

        public async Task<PageInfo> Handle(TraceableSelectCommand request, CancellationToken cancellationToken)
        {
            var info = await traceableService.GetValues(x => !x.IsDel);
            var selInfo = info.AsQueryable();
            if (!string.IsNullOrEmpty(request.batch))
            {
                selInfo = selInfo.Where(x => x.Batch == request.batch);
            }
            if (request.shelflife != 0)
            {
                selInfo = selInfo.Where(x => x.Shelflife == request.shelflife);
            }
            if (!string.IsNullOrEmpty(request.number))
            {
                selInfo = selInfo.Where(x => x.Number == request.number);
            }
            var res = new List<TraceableDto>();
            foreach (var item in selInfo)
            {
                var gname = goodsService.GetAsync(item.Gid).Result.Name;
                var dto = new TraceableDto
                {
                    Gname = gname,
                    Batch = item.Batch,
                    CreatePeople = item.CreatePeople,
                    CreateTime = item.CreateTime,
                    Gid = item.Gid,
                    Id = item.Id,
                    Images = item.Images,
                    Number = item.Number,
                    ProduceEnterprise = item.ProduceEnterprise,
                    Shelflife = item.Shelflife,
                    UpdateePeople = item.UpdateePeople,
                    UpdateTime = item.UpdateTime,
                };
                res.Add(dto);
            }
            var result = new PageInfo();
            if (!string.IsNullOrEmpty(request.gName))
            {
                res = res.Where(x => x.Gname.Contains(request.gName)).ToList();
            }
            result.totalCount = res.Count;
            result.pageCount = (int)Math.Ceiling(result.totalCount * 1.0 / request.pageSize);
            res = res.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            result.list = res;

            return result;
        }
    }
}
